﻿//#define INJECT_CONFIG_OBJECT

// Need to pass hWnd when call ShowForm() ? : No need. So far, found Summit from this Constructor
using System;
//using System.Collections.Generic;
//using System.Text;
using System.Windows;
//using System.Windows.Controls;
//using System.Windows.Data;
//using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
using CustomControls;
using System.Threading;

namespace DienVu
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : CustomWindow
    {
        private System.Windows.Forms.Form g_formSummit;
        private System.Windows.Forms.Form g_formJob;
        private DienLib.SummitLib.JobLib g_jobLib;
        private DienLib.ReportLib.FarPac g_farPac;
        private DienLib.SummitLib.SummitFormLib g_summitLib;
        private string g_FarpacPath = null;

        #region VARIABLE needed when init this Class
        private static MainWindow _form = null;
        //private static Thread _threadSummit = null;
        private static Thread _threadAuto = null;
        private static DienLib.ReportLib.Configuration _config = null;
        private static string _configPath = null;
        //private static IntPtr _hWndProc = IntPtr.Zero;
        //private static IntPtr _hWndSummit = IntPtr.Zero;
        //private static IntPtr _hWndNewJob = IntPtr.Zero;
        //private static Process _summitProc = null;
        #endregion


        public MainWindow()
        {
            InitializeComponent();
            try { g_formSummit = DienLib.SummitLib.Command.GetSummitMainForm(); g_formSummit.FormClosed += new System.Windows.Forms.FormClosedEventHandler(_formSummit_FormClosed); }
            catch (Exception ex) { MessageBox.Show("Can't get Summit Form from Handle in DemoSummit Constructor()\r\n" + ex.Message, "ERROR ! CLOSE \"Demo SUMMIT\" NOW !", MessageBoxButton.OK, MessageBoxImage.Error); return; }
            g_summitLib = new DienLib.SummitLib.SummitFormLib(g_formSummit);
        }

        public MainWindow(string pathFarpac)
        {
            InitializeComponent();
            this.butFarPac.IsEnabled = false;
            g_FarpacPath = pathFarpac;

            try { g_formSummit = DienLib.SummitLib.Command.GetSummitMainForm(); g_formSummit.FormClosed += new System.Windows.Forms.FormClosedEventHandler(_formSummit_FormClosed); }
            catch (Exception ex) { MessageBox.Show("Can't get Summit Form from Handle in DemoSummit Constructor()\r\n" + ex.Message, "ERROR ! CLOSE \"Demo SUMMIT\" NOW !", MessageBoxButton.OK, MessageBoxImage.Error); return; }
            g_summitLib = new DienLib.SummitLib.SummitFormLib(g_formSummit);
        }

        /// <summary>
        /// 1st Method called during injecting ... This will happen in Mainthread of the Injected Process
        /// </summary>
        /// <param name="hWnd">This should be the Handle of any Main Window Handle of OpenJob.UI Process</param>
#if INJECT_CONFIG_OBJECT
        public static void ShowForm(IntPtr hWnd, DienLib.OfficeLib.Configuration config)
#else
        public static void ShowForm(IntPtr hWnd, string configPath, string farpacPath = null)
#endif
        {
            //_Don't use hWnd
            //_hWndProc = hWnd;
            //_threadSummit = Thread.CurrentThread;
#if INJECT_CONFIG_OBJECT
            _config = config;
#else
            _configPath = configPath; // Do not Parse Excel file here because this method is being run in Injection Code. Better do it in FormLoad
#endif
            // START NEW THREAD FOR DEMO SUMMIT GUI
            if (farpacPath == null) NewThreadForm();
            else NewThreadForm(farpacPath);
        }

        private static void NewThreadForm(string farpacPath = null)
        {
            //DienLib.WinAPI.WriteNotePad("NEW THREAD FORM");
            if (_threadAuto == null)
            {
                //DienLib.WinAPI.WriteNotePad("THREAD AUTO NULL");
                _threadAuto = new Thread(delegate()
                {
                    //DienLib.WinAPI.WriteNotePad("Sap SHOW FORM !");
                    if (_form == null)
                    {
                        //DienLib.WinAPI.WriteNotePad("_FORM NULL"); 
                        if (farpacPath == null) _form = new MainWindow();
                        else _form = new MainWindow(farpacPath);
                    } //_frmSummit create new Instance everytime create new job
                    //Window.Application.Run(_form); //Block HERE

                    //DienLib.WinAPI.WriteNotePad("Chuan bi SHOW FORM !");
                    _form.ShowDialog(); //Block HERE

                    try
                    {
                        _form = null;
                        _threadAuto = null;
                        //_threadAuto.Abort();
                    }
                    catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR"); }
                });
                _threadAuto.SetApartmentState(ApartmentState.STA);
                _threadAuto.Start();
            }
            else
            {
                MessageBox.Show("THREAD AUTO NOT NULL", "ERROR");
            }
        }

        /// <summary>
        /// This will be called by Summit Main Form Close Event (in Summit Main Form Thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _formSummit_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            g_formSummit.FormClosed -= _formSummit_FormClosed; // Detach or No need ?
            _form = null; _threadAuto = null;  // Free Up Static Resource
            this.Dispatcher.BeginInvoke((Action)(() => this.Close()), null); // Non-static (Private) Managed Object (_jobLib, ...) will be free up automatically after form.close() by GC
        }

        private void OnOfficeButtonClick(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("OfficeButton notification received in derived Window class!");
        }

        private void OnHelp(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Display Help file!");
        }

        private void butFarPac_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fDialog = new System.Windows.Forms.OpenFileDialog();
            fDialog.Title = "Open DEMO FARPAC Excel File";
            fDialog.Filter = "DemoFarpac EXCEL File|*.xlsx";
            fDialog.InitialDirectory = _config[DienLib.ReportLib.Configuration.Paths.FOLDER_FARPAC];
            if (fDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try { g_farPac = new DienLib.ReportLib.FarPac(fDialog.FileName, _config); }
                catch (Exception ex) { MessageBox.Show("Not a FARPAC file or unsupported version ! Please try another !\r\n" + ex.Message, "NOT SUPPORTED FARPAC VERSION"); }
            }
        }

        private void butStartNewJob_Click(object sender, RoutedEventArgs e)
        {
            if (g_formSummit.Visible == true)
            {   // If Form Summit Appear then Check Duplicate & then Click
                // CHECK IF DUPLICATE WITH CURRENT FARPAC : BY TICKET NUMBER
                string ticket = g_farPac.SaleNumber;//"9351453";
                //MessageBox.Show("1");
                int dupTimes = g_summitLib.FoundDuplicateTicket(ticket);
                if (dupTimes > 1)
                {   // POPUP MANUAL CLICK OR DELETE
                    //MessageBox.Show("2");
                    return;
                }
                else if (dupTimes == 1)
                {   // One Package Duplicate => Reopen
                    //MessageBox.Show("3");
                    DienLib.PopUp.PopUpResult res =
                        DienLib.PopUp.PopUpOKCancel.ShowDialog("Man ! Only \"1 DUPLICATE FOUND\" mean : You already create this Package before once ! Now 2 CHOICES :" +
                        "\r\n\r\n         \"1. CLICK OK then REOPEN THIS PACKAGE\", the soft will wait for \"you Click Open\"" +
                        "\r\n         \"2. Click CANCEL then CHECK & DELETE THIS PACKAGE\", you can create a new job again without Duplicate",
                        string.Format("REOPEN EXISTING JOB PACKAGE - Ticket : \"{0}\"", ticket));
                    if (res == DienLib.PopUp.PopUpResult.CANCEL) return; // If he doesn't want Reopen, return (for delete duplicate)
                    g_summitLib.PerformDoubleClickActiveJob();
                }
                else
                {   // No Duplicate => Create new Job by Auto Click
                    //MessageBox.Show("4");
                    System.Windows.Forms.ToolStripSplitButton _newJob = DienLib.Reflector.GetField<System.Windows.Forms.ToolStripSplitButton>(g_formSummit, "tsNewJob");
                    _newJob.GetCurrentParent().BeginInvoke((System.Windows.Forms.MethodInvoker)delegate() { _newJob.PerformButtonClick(); });
                }
            }
            //MessageBox.Show("5");
            // Else Summit not Visible or Duplicate One with OK or Already Create New JOb => just find Job Main Form
            try { g_formJob = DienLib.SummitLib.Command.GetJobMainForm(); }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }
            //MessageBox.Show("6");
            if (g_formJob == null) { MessageBox.Show("No Form Job ! Try again later !"); return; }
            //MessageBox.Show("7");
            g_jobLib = new DienLib.SummitLib.JobLib(g_formJob);
        }

        private void butPage1_Click(object sender, RoutedEventArgs e)
        {
            if (g_jobLib == null)
            {
                MessageBox.Show("Job Window not found or maybe you forget Click NEW JOB !\r\nPlease click \"START an NEW JOB\" first !", "WARNING : Click \"START & NEW JOB\" FIRST!");
                return;
            }

            try
            {
                DienLib.WinAPI.SetBlinkSpeed(DienLib.BlinkSpeed.BLINK_NORMAL);
                try { g_jobLib.ActivateTabPage1(); }
                catch (Exception ex) { MessageBox.Show("Cannot Activate TabPage1. Something wrong !\r\n" + ex.Message, "Error Activate TabPage1"); }

                try { g_jobLib.IsTrainingJob = true; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Training Job. Something wrong !\r\n" + ex.Message, "Error Training Job"); }

                try { g_jobLib.Customer = g_farPac.Customer; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Customer. Something wrong !\r\n" + ex.Message, "Error Customer"); }
                try { g_jobLib.CompanyMan = g_farPac.CompanyMan; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Company Man. Something wrong !\r\n" + ex.Message, "Error Company Man"); }
                try { g_jobLib.WellType = g_farPac.WellType; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Job Well Type. Something wrong !\r\n" + ex.Message, "Error Job Well Type"); }
                try { g_jobLib.SaleNumber = g_farPac.SaleNumber; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Sale Number. Something wrong !\r\n" + ex.Message, "Error Sale Number"); }
                try { g_jobLib.PrimaryServiceCenter = g_farPac.PrimaryServiceCenter; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Primary Service Center. Something wrong !\r\n" + ex.Message, "Error Primary Service Center"); }
                try { g_jobLib.SecondaryServiceCenter = g_farPac.SecondaryServiceCenter; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Secondary Service Center. Something wrong !\r\n" + ex.Message, "Error Secondary Service Center"); }
                try { g_jobLib.JobType = DienLib.SummitLib.Enums.JobType.PERF; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Job Type. Something wrong !\r\n" + ex.Message, "Error Job Type"); }
                try { g_jobLib.RiglessOperation = true; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Rigless Operation. Something wrong !\r\n" + ex.Message, "Error Rigless Operation"); }
                try { g_jobLib.WellName = g_farPac.WellName; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Well Name. Something wrong !\r\n" + ex.Message, "Error Well Name"); }
                try { g_jobLib.Location = g_farPac.Location; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Location. Something wrong !\r\n" + ex.Message, "Error Location"); }
                try { g_jobLib.API_UWI(); }
                catch (Exception ex) { MessageBox.Show("Cannot Set API_UWI. Something wrong !\r\n" + ex.Message, "Error API_UWI"); }
                try { g_jobLib.ShipToNumber = g_farPac.ShipTo; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Ship To Number. Something wrong !\r\n" + ex.Message, "Error Ship To Number"); }
                try { g_jobLib.Country = g_farPac.Country; }
                catch (Exception ex) { MessageBox.Show("Cannot Set Country. Something wrong !\r\n" + ex.Message, "Error Job Type"); }
                try { g_jobLib.State = DienLib.SummitLib.Enums.State.NA; }
                catch (Exception ex) { MessageBox.Show("Cannot Set State. Something wrong !\r\n" + ex.Message, "Error Job Type"); }
                try { g_jobLib.CO2Present = DienLib.SummitLib.Enums.CO2Present.UNKNOWN; }
                catch (Exception ex) { MessageBox.Show("Cannot Set CO2 Present. Something wrong !\r\n" + ex.Message, "Error CO2 Present"); }
                try { g_jobLib.H2SPresent = DienLib.SummitLib.Enums.H2SPresent.UNKNOWN; }
                catch (Exception ex) { MessageBox.Show("Cannot Set H2S Present. Something wrong !\r\n" + ex.Message, "Error H2S Present"); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\nTRY TO START AGAIN STEP BY STEP & IN ORDER !", "WARNING : Something wrong when fill PAGE1 !");
            }
        }

        private void butPage2_Click(object sender, RoutedEventArgs e)
        {
            if (g_jobLib == null)
            {
                MessageBox.Show("Job Window not found or maybe you forget Click NEW JOB !\r\nPlease click \"START an NEW JOB\" first !", "WARNING : Click \"START & NEW JOB\" FIRST!");
                return;
            }

            try
            {
                DienLib.WinAPI.SetBlinkSpeed(DienLib.BlinkSpeed.BLINK_NORMAL);
                g_jobLib.ActivateTabPage2();

                g_jobLib.ServiceCoordinator = g_farPac.ServiceCoordinator;
                g_jobLib.ServicePlanner = DienLib.SummitLib.Enums.ServicePlanner.YUPHA;
                g_jobLib.WellFluid = g_farPac.WellFluid;

                DienLib.WinAPI.SetBlinkSpeed(DienLib.BlinkSpeed.BLINK_FAST);
                g_jobLib.UnitStyle = g_farPac.UnitStyle;
                g_jobLib.DrillDepth = g_farPac.DrillDepth; //"4321";
                g_jobLib.JobMD = g_farPac.JobMD; //"4001";
                g_jobLib.JobTVD = g_farPac.JobTVD; //"3001";
                g_jobLib.MaxTemp = g_farPac.MaxTemp; //"325";
                g_jobLib.FormationPressure = g_farPac.FormationPressure; //"3003";
                g_jobLib.WellheadPressure = g_farPac.WellheadPressure; //"2201";
                g_jobLib.FluidLevel = g_farPac.FluidLevel; //"17";
                g_jobLib.MudWeight = "1";
                g_jobLib.MudResistivity = "1";
                g_jobLib.MudResTemp = "1";
                g_jobLib.FilterateResistivity = "1";
                g_jobLib.FilterateResTemp = "1";
                g_jobLib.CakeResistivity = "1";
                g_jobLib.CakeResTemp = "1";
                g_jobLib.BitSize = g_farPac.BitSize; // "6.125";
                g_jobLib.ChlorideConcentration = "1";
                g_jobLib.MinID = g_farPac.MinID; // "2.813";
                g_jobLib.MinIDDepth = g_farPac.MinIDDepth; // "237";
                g_jobLib.MaxDeviation = g_farPac.MaxDeviation; // "21.56";
                g_jobLib.MaxDevDepth = g_farPac.MaxDevDepth; // "1000";
                g_jobLib.KickoffDepth = g_farPac.KickoffDepth; // "174";
                g_jobLib.MaxDogleg = g_farPac.MaxDogleg; // "0.25";
                g_jobLib.MaxDoglegDepth = g_farPac.MaxDoglegDepth; // "2000";
                g_jobLib.WellDirectionTD = g_farPac.WellDirectionTD; // "9";
                g_jobLib.WellDeviationTD = g_farPac.WellDeviationTD; // "10";
                g_jobLib.WaterDepth = g_farPac.WaterDepth; // "11";
                g_jobLib.SeaBedTemp = g_farPac.SeaBedTemp; // "12";
                g_jobLib.ShowPerfInterval = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\nTRY TO START AGAIN STEP BY STEP & IN ORDER !", "WARNING : Something wrong when fill PAGE2 !");
            }
        }

        private void butPage3_Click(object sender, RoutedEventArgs e)
        {
            if (g_jobLib == null)
            {
                MessageBox.Show("Job Window not found or maybe you forget Click NEW JOB !\r\nPlease click \"START an NEW JOB\" first !", "WARNING : Click \"START & NEW JOB\" FIRST!");
                return;
            }

            try
            {
                DienLib.WinAPI.SetBlinkSpeed(DienLib.BlinkSpeed.BLINK_NORMAL);
                g_jobLib.ActivateTabPage3();
                g_jobLib.LoggingEngineer = g_farPac.LoggingEngineer;
                g_jobLib.QualityCoordinator = DienLib.SummitLib.Enums.QualityCoordinator.JOSE;
                g_jobLib.FillExplosiveSafetyList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\nTRY TO START AGAIN STEP BY STEP & IN ORDER !", "WARNING : Something wrong when fill PAGE3 !");
            }

            try { g_jobLib.AddService(g_farPac.NonPerfRuns); }
            catch (Exception ex) { MessageBox.Show("Cannot Add Services Run Correctly !\r\n" + ex.Message, "Add Services FAIL"); }

            try { g_jobLib.AddPerforation(g_farPac.PerfRuns); }
            catch (Exception ex) { MessageBox.Show("Cannot Add Perforation Run Correctly !\r\n" + ex.Message, "Add Perforation FAIL"); }
        }

        private void butExportMail_Click(object sender, RoutedEventArgs e)
        {
            // Check if Document[0-9] ghi lai 0-9
            // Generate Hit List
            // Check again if see no increase then that one.
            // PopUpOK save that file -> default name to desktop

            // Back to Summit Job Packet
            // SendMessage to click Save & Exit Button Toolstrip
            // Find Exact Window "Missing PSL Required Data", Send Click NO (YES return No continue Save/Exit)
            // Find Exact Window "Save/Exit", Send Button Click YES

            // Wait for Summit Form Visible = true & Not Working Bar Running (Idle)
            // Open Tree Nodes. For each Node Get Text
            // Check if Text have Same WellNo, ShipTo, UAI_WAP
            //UltraTreeView.Nodes : TreeNodesCollection

            //BK-15-M:  :  (Ship To : 2584528) : AFEBO4ICLBK62K567EO
            //BK-15-K:  :  (Ship To : 2916133) : AFEBO4ICLBK62K9OG01
            //BK-S3-E:  :  (Ship To : 9876543210) : AFEBO4ICLBK5XX3GZRC

            // Select that Nodes
            // Send Click to Export
            // If Find Window se "Alert ..." Send OK
            // Find Window Exact "Export Job Packet"
            // Ghi lai ten Packet -> Co the Rename
            // Choose Desktop
            // btnImport.PerformClick() : Infragistics ultrabutton
            // 
        }

        private void CustomWindow_Loaded(object sender, RoutedEventArgs e)
        {
#if !INJECT_CONFIG_OBJECT
            //MessageBox.Show("_configPath");
            _config = new DienLib.ReportLib.Configuration(_configPath);
            if (g_FarpacPath != null)
                try { g_farPac = new DienLib.ReportLib.FarPac(g_FarpacPath, _config); }
                catch (Exception ex) { MessageBox.Show("Not a FARPAC file or unsupported version ! Please try another !\r\n" + ex.Message, "NOT SUPPORTED FARPAC VERSION"); }
            //MessageBox.Show(_config[DienLib.ReportLib.Configuration.Paths.FOLDER_FARPAC]);
#endif
        }
    }
}
